package com.app.business.web;

import com.app.business.model.*;
import com.app.business.service.*;
import com.app.system.jpa.PageBean;
import com.app.system.permission.model.Department;
import com.app.system.permission.model.UserInfo;
import com.app.system.permission.service.DataDictService;
import com.app.system.permission.service.DepartmentService;
import com.app.system.permission.service.UserInfoService;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.Style;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zt on 2021-06-24
 */
@Controller
@RequestMapping("/business/worker/*")
public class WorkerInfoController {

    @Autowired
    private WorkerInfoService workerInfoService;
    @Autowired
    private WageService wageService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private OperationService operationService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private NoHouseWorkerApplyService noHouseWorkerApplyService;
    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private NoStandardWorkerApplyService noStandardWorkerApplyService;
    @Autowired
    private DepartmentService departmentService;

    /**
     * 无房职工列表
     */
    @RequestMapping("noHouseList")
    @RequiresPermissions("noHouse:noHouseList")
    public void noHouseList(ModelMap modelMap) {
    }

    /**
     * 无房职工列表数据
     */
    @RequestMapping("loadNoHouseList")
    @ResponseBody
    @RequiresPermissions("noHouse:loadNoHouseList")
    public Map loadNoHouseList(HttpServletRequest request) {
        Map<String,String> sbFlagMap=dataDictService.getMapByParentNameForValue_Name("申报状态");
        int sbFlag=ParamUtils.getInt(request,"sbFlag",0);
        List<Map> listData = Lists.newArrayList();
        Map<String, String> codeMap = departmentService.getAllNameBycode();
        PageBean<WorkerInfo> familyPageBean = this.workerInfoService.getWorkerInfoPage();
        Map<Integer,NoHouseWorkerApply> map=noHouseWorkerApplyService.getNoHouseWorkerApplyByIdMap();
        List<WorkerInfo> workerInfoList = familyPageBean.getDatas();
        if (CollectionUtils.isNotEmpty(workerInfoList)) {
            Map<String, Object> item;
            for (WorkerInfo workerInfo : workerInfoList) {
                item = Maps.newHashMap();
                item.put("id", workerInfo.getId());
                item.put("name", StringUtils.getNotNull(workerInfo.getName()));
                item.put("idCard", StringUtils.getNotNull(workerInfo.getIdCard()));
                item.put("wages", workerInfo.getWages());
                item.put("livingAddress", StringUtils.getNotNull(workerInfo.getLivingAddress()));
                item.put("workedYears", BigDecimalUtils.getNotNull(workerInfo.getWorkedYears()));
                item.put("startWorkingDate", String.valueOf(workerInfo.getStartWorkingDate()));
                item.put("joinWorkingDate", String.valueOf(workerInfo.getJoinWorkingDate()));
                item.put("retireDate", String.valueOf(workerInfo.getRetireDate()));
                item.put("nowZw", workerInfo.getPosition().getName());
                if (workerInfo.getNum()!=null){
                    item.put("recordNo",workerInfo.getRecordNo()+new DecimalFormat("0000").format(workerInfo.getNum()));
                }else{
                    item.put("recordNo","");
                }
                String status="未申报";
                if (map.get(workerInfo.getId())!=null){
                    status="已申报";
                }
                item.put("status",status);
                item.put("depName",codeMap.get(workerInfo.getDepartmentCode()));
                if (sbFlag!=0){
                    if (sbFlagMap.get(String.valueOf(sbFlag)).equals(status)) {
                        listData.add(item);
                    }
                }else{
                    listData.add(item);
                }
            }
        }
        return LayUiUtils.page(familyPageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 无房职信息登记
     */
    @RequestMapping("noHouseInfo")
    public void noHouseInfo(HttpServletRequest request, ModelMap modelMap) {
        UserInfo userInfo=WebUtils.getLoginUserInfo();
        String departmentCode=userInfo.getDepartment().getCode();
        Map<String,String> depByNumMap=dataDictService.getMapByParentNameForValue_Name("编号规则");
        String record="JGBJ-";
        if (departmentCode.length()>3){
            record=depByNumMap.get(departmentCode.substring(0,4));
        }
        List<Position> positionList=positionService.getPositionList();
        int workerId = ParamUtils.getInt(request, "workerId", 0);
        WorkerInfo workerInfo = workerInfoService.findOne(workerId);
        String nowPosition = "";
        String txPosition = "";
        String num="";
        if (workerInfo == null) {
            workerInfo = new WorkerInfo();
            num=this.getRecordNoAndNum(record);
        } else {
            if(workerInfo.getNum()==null){
                num="";
            }else{
                num=new DecimalFormat("0000").format(workerInfo.getNum());
            }

            if (workerInfo.getPosition() != null) {
                nowPosition = workerInfo.getPosition().getCode();
            }
            if (workerInfo.getRetirePosition() != null) {
                txPosition = workerInfo.getRetirePosition().getCode();
            }
        }
        modelMap.addAttribute("workerInfo", workerInfo);
        modelMap.addAttribute("nowPosition", nowPosition);
        modelMap.addAttribute("txPosition", txPosition);
        modelMap.addAttribute("positionList", positionList);
        modelMap.addAttribute("num", num);
        modelMap.addAttribute("record", record);
    }

    /**
     * 获取最新编号
     * @return
     */
    public String getRecordNoAndNum(String record){
        DecimalFormat decimalFormat = new DecimalFormat("0000");
        String num="";
        int number1=Integer.valueOf(workerInfoService.getRecordNum(record));
        int number2=Integer.valueOf(noStandardWorkerApplyService.getRecordNum(record));
        if (number1>number2){
            num=(decimalFormat.format(number1+1));
        }else{
            num=(decimalFormat.format(number2+1));
        }
        return num;
    }

    /**
     * 无房职信息保存
     */
    @RequestMapping("workerInfoSave")
    @ResponseBody
    public synchronized Response workerInfoSave(HttpServletRequest request) {
        int workerId = ParamUtils.getInt(request, "workerId", 0);
        String nowPosition = ParamUtils.getString(request, "nowPosition", "");
        String txPosition = ParamUtils.getString(request, "txPosition", "");
        //获取职务对象
        Position position = positionService.getPositionByCode(nowPosition);
        Position retirePosition = positionService.getPositionByCode(txPosition);

        WorkerInfo workerInfo = this.workerInfoService.findOne(workerId);
        List<Wage> wageList = new ArrayList<>();
        // 1新增 2修改
        int operateType=2;
        if (workerInfo == null) {
            operateType=1;
            workerInfo = new WorkerInfo();
            UserInfo userInfo=WebUtils.getLoginUserInfo();
            workerInfo.setDepartmentCode(userInfo.getDepartment().getCode());
            if (nowPosition != null) {
                workerInfo.setPosition(position);
            }
            if (txPosition != null) {
                workerInfo.setRetirePosition(retirePosition);
            }

            if (!"".equals(workerInfo.getWages())) {
                wageList = wageService.getWageListByYearAndMonth(2019, 9);
            }
        } else {
            if (nowPosition != null) {
                workerInfo.setPosition(position);
            }
            if (txPosition != null) {
                workerInfo.setRetirePosition(retirePosition);
            }
        }
        WebUtils.bind(request, workerInfo);
        workerInfoService.save(workerInfo);
        wageService.saveWageList(wageList, workerInfo);
        //操作记录
        operationService.getOperationHisLog(workerInfo.getName(),workerInfo.getId(),operateType,1,workerInfo);
        return new Response("0001", "保存成功");
    }

    /**
     * 无房职信息查看
     */
    @RequestMapping("noHouseView")
    public void noHouseView(HttpServletRequest request, ModelMap modelMap) {
        int workerId = ParamUtils.getInt(request, "workerId", 0);
        WorkerInfo workerInfo = workerInfoService.findOne(workerId);
        Precondition.checkAjaxArguement(workerInfo != null, "1111", "数据错误！");
        modelMap.addAttribute("workerInfo", workerInfo);
    }
    /**
     * 无房职工删除
     *
     * @param request
     * @return
     */
    @RequestMapping("delNoHouse")
    @ResponseBody
    public Response delNoHouse(HttpServletRequest request) {
        int workerId = ParamUtils.getInt(request, "workerId", 0);
        NoHouseWorkerApply noHouseWorkerApply = noHouseWorkerApplyService.getNoHouseWorkerApplyByWorkId(workerId);
        if (noHouseWorkerApply!=null){
            return new Response("0002", "请先删除已经申报的数据，再删除基础数据");
        }
        WorkerInfo workerInfo = workerInfoService.findOne(workerId);
        String name=workerInfo.getName();
        if (workerInfo != null && workerInfo.getId() != null) {
            if (noHouseWorkerApply != null) {
                noHouseWorkerApplyService.delete(noHouseWorkerApply.getId());
            }
            //操作记录
            operationService.getOperationHisLog(name,workerInfo.getId(),3,1,workerInfo);
            //删除工资表
            wageService.deleteWageByWorkerInfoId(workerId);
            workerInfoService.delete(workerId);
            return new Response("0001", "删除成功");

        } else {
            return new Response("0002", "删除失败");
        }
    }
    /**
     * 身份证号码验证
     */
    @RequestMapping("loadWorkerInfoForApply")
    @ResponseBody
    public Response loadWorkerInfoForApply(HttpServletRequest request, ModelMap modelMap) {
        String idCard = ParamUtils.getString(request, "idCard", "");
        WorkerInfo workerInfo = workerInfoService.getWorkerInfoByIdCard(idCard);
        if (workerInfo!=null){
            return new Response("0002","身份证号重复请重新填写");
        }else{
            Response response = new Response<>();
            response.setCode("0001");
            return response;

        }
    }
    @RequestMapping("checkRecordNo")
    @ResponseBody
    public Response checkRecordNo(HttpServletRequest request) {
        int num = ParamUtils.getInt(request, "num", 0);
        String recordNo= ParamUtils.getString(request, "recordNo", "");
        int workerId = ParamUtils.getInt(request, "workerId", 0);
        WorkerInfo workerInfo1=workerInfoService.getWorkerInfoById(workerId);
        WorkerInfo workerInfo = workerInfoService.getWorkerInfoByNum(num,recordNo);
        NoStandardWorkerApply noStandardWorkerApply = noStandardWorkerApplyService.getWorkerInfoByNum(num,recordNo);
        if (workerInfo==null && noStandardWorkerApply==null){
            Response response = new Response<>();
            response.setCode("0001");
            return response;
        }else if (workerInfo1.getNum()==num){
            Response response = new Response<>();
            response.setCode("0001");
            return response;
        }else{
            return new Response("0002","备案编号重复请重新填写");
        }
    }
}
